package com.sekill.miaosha.mq;

import com.alibaba.fastjson.JSON;
import com.rabbitmq.client.Channel;
import com.seckill.system.api.RemoteOrderService;
import com.seckill.system.api.domain.Order;
import com.sekill.miaosha.mapper.TbStockMapper;
import com.sekill.miaosha.utils.IdWorker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.Map;

@Component
public class ConsumerService {

    private static Logger log = LoggerFactory.getLogger(MQReceiver.class);

    @Autowired
    TbStockMapper tbStockMapper;

    @Autowired
    RemoteOrderService remoteOrderService;

    @Autowired
    RedisTemplate redisTemplate;

    @RabbitListener(queues = "queue_work")
    public void receiveMessage(Map<String,Object> msg,Channel channel) {
        System.err.println(msg);



        Order order = new Order();
        order.setOrderId((Long) msg.get("orderid"));
        System.err.println((Long) msg.get("orderid"));
        order.setTotalPay((BigDecimal) msg.get("seckillPrice"));
        order.setActualPay((BigDecimal) msg.get("seckillPrice"));
        order.setPostFee(new Long(10));
        order.setShippingName("顺丰快递");
        order.setJifen("100");
        order.setYouhui("不可用");
        System.out.println(msg.get("userId"));
        order.setUserId((Long) msg.get("userId"));
        order.setCreateTime(new Date());
        order.setSkuId((Long) msg.get("skuId"));
        Long save = remoteOrderService.save(order);
        System.out.println(save);
        redisTemplate.opsForValue().set(save+"",2);
        int skuId = tbStockMapper.updatestock((Long) msg.get("skuId"));

    }

    public static <T> T stringToBean(String str, Class<T> clazz) {
        if(str == null || str.length() <= 0 || clazz == null) {
            return null;
        }
        if(clazz == int.class || clazz == Integer.class) {
            return (T)Integer.valueOf(str);
        }else if(clazz == String.class) {
            return (T)str;
        }else if(clazz == long.class || clazz == Long.class) {
            return  (T)Long.valueOf(str);
        }else {
            return JSON.toJavaObject(JSON.parseObject(str), clazz);
        }
    }
}
